package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.ProducerOwnCategory;
import model.Product;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile {
	public static void uploadFile(HttpServletRequest request, Product product,
			ProducerOwnCategory poc) {
		FileOutputStream outStream = null;
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("utf-8");

					if (name.equalsIgnoreCase("productName"))
						product.setProductName(value);
					if (name.equalsIgnoreCase("quantity"))
						product.setQuantity(Integer.valueOf(value));
					if (name.equalsIgnoreCase("price"))
						product.setPrice(Integer.valueOf(value));
					if (name.equalsIgnoreCase("producerId"))
						poc.setProducerId(Integer.valueOf(value));
					if (name.equalsIgnoreCase("categoryId"))
						poc.setCategoryId(Integer.valueOf(value));
					if (name.equalsIgnoreCase("description"))
						product.setDescription(value);
					if (name.equalsIgnoreCase("productId"))
						product.setProductId(Integer.valueOf(value));
				} else {
					String fileName = item.getName();

					if (!fileName.equalsIgnoreCase("")) {
						product.setImage(fileName);
						File file = new File(
								"E:\\images\\" + fileName);

						if (!file.exists()) {
							outStream = new FileOutputStream(file);
							InputStream stream = item.getInputStream();
							byte[] buffer = new byte[1024];
							while (true) {
								int bytes = stream.read(buffer);
								if (bytes <= 0)
									break;
								outStream.write(buffer, 0, bytes);
							}
							outStream.flush();
						}
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (outStream != null)
					outStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
